import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { requiresGuest: true }
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/AgentSelection.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/chat/:agentId',
      name: 'chat',
      component: () => import('../views/VoiceChat.vue'),
      props: true,
      meta: { requiresAuth: true }
    },
    {
      path: '/history',
      name: 'history',
      component: () => import('../views/ChatHistory.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/history/:sessionId',
      name: 'session-detail',
      component: () => import('../views/SessionDetail.vue'),
      props: true,
      meta: { requiresAuth: true }
    },
    {
      path: '/knowledge',
      name: 'knowledge',
      component: () => import('../views/KnowledgeBase.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/performance',
      name: 'performance',
      component: () => import('../views/PerformanceMonitor.vue'),
      meta: { requiresAuth: true }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化用户信息
  if (!userStore.user && userStore.token) {
    userStore.initUser()
  }
  
  // 需要登录的页面
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
    return
  }
  
  // 已登录用户访问登录页面，重定向到首页
  if (to.meta.requiresGuest && userStore.isLoggedIn) {
    next('/')
    return
  }
  
  next()
})

export default router
